package com.argrace.smart.activity.devicerelation;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.activity.DeviceControl_FuKongActivity;
import com.argrace.smart.activity.DeviceControl_ShuiJinActivity;
import com.argrace.smart.activity.DeviceModifyActivity;
import com.argrace.smart.activity.QingJingListActivity;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.glide.GliderImageLoaderUtil;
import com.argrace.smart.model.LocalDb_RelationDeviceTable;
import com.argrace.smart.ui.DrawableSwitch;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.Logg;
import com.zhouyou.view.seekbar.SignSeekBar;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by argrace_dev_1 on 2018/3/2.
 */

public class DeviceRelation_BaoJingActivity extends BaseActivity {
    private ImageView img;
    private TextView dianliang_text, xinhaoqiangdu_text;
    private SignSeekBar dianliang, xinhaoqiangdu;
    private TextView baojing1_text, baojing2_text, baojing3_text;
    private DrawableSwitch baojing1, baojing2, baojing3;
    LinearLayout dianliang_ll, xinhaoqiangdu_ll, baojing1_ll, baojing2_ll, baojing3_ll;
    //此处开始修改为关联设备增加的属性
    String uuid, model;
    LinearLayout relationdevice_ll;
    TextView relationdevice_text;
    private int qingJingTable_id = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicecontrol_baojing);
        init();
    }

    private void init() {
        MineZigBeeDeviceListEntity entity = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        uuid = entity.getUuid();
        model = entity.getModel();
        setView();
        setTitle(true, false, "添加关联");
        showRight(true, R.mipmap.head_title_tick);
        //点击右上角保存此时设备状态与关联场景
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        //初始化后，数据库查询当前设备关联情况，无关联则查询最新状态
        if (false) {

        } else {
            getDeviceDetailInfo();
        }


    }

    //烟雾、门磁、煤气、人体,后加入的水浸
    private void save() {
        LocalDb_RelationDeviceTable relationDeviceTable = new LocalDb_RelationDeviceTable();
        relationDeviceTable.setUuid(uuid);
        relationDeviceTable.setModel(model);
        Map<String, String> trigger_condition = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        if (model.equals(ConstantConfigure.MODEL_YANWUTANCEQI)) {
            //电量、信号强度、报警
            if (baojing1.isSwitchOn()) {
                sb.append("\"SmokeAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"SmokeAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
            sb.append("\"BatteryPercentage\" :");
            Key_ValueEntity entity_dianliang = new Key_ValueEntity();
            entity_dianliang.setValue(String.valueOf(dianliang.getProgress()));
            sb.append(entity_dianliang.toString());
            sb.append(",");
            sb.append("\"Rssi\" :");
            Key_ValueEntity entity_xinhao = new Key_ValueEntity();
            entity_xinhao.setValue(String.valueOf(xinhaoqiangdu.getProgress()));
            sb.append(entity_xinhao.toString());
            sb.append(",");
        }
        if (model.equals(ConstantConfigure.MODEL_MENCIGANYING)) {
            //0（关闭） 1（打开）门磁打开
            if (baojing1.isSwitchOn()) {
                sb.append("\"ContactAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"ContactAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
            //0（正常） 1（被撬）如果是打开则被撬
            if (baojing2.isSwitchOn()) {
                sb.append("\"TamperAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"TamperAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }

            sb.append("\"BatteryPercentage\" :");
            Key_ValueEntity entity_dianliang = new Key_ValueEntity();
            entity_dianliang.setValue(String.valueOf(dianliang.getProgress()));
            sb.append(entity_dianliang.toString());
            sb.append(",");
            sb.append("\"Rssi\" :");
            Key_ValueEntity entity_xinhao = new Key_ValueEntity();
            entity_xinhao.setValue(String.valueOf(xinhaoqiangdu.getProgress()));
            sb.append(entity_xinhao.toString());
            sb.append(",");

        }
        if (model.equals(ConstantConfigure.MODEL_MEIQITANCEQI)) {
            //枚举值：0（正常） 1（燃气泄漏）
            if (baojing1.isSwitchOn()) {
                sb.append("\"GasAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
            } else {
                sb.append("\"GasAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
            }
        }
        if (model.equals(ConstantConfigure.MODEL_RENTIGANYING)) {
            //0（正常） 1（检测有人）如果是打开则有人
            if (baojing1.isSwitchOn()) {
                sb.append("\"MotionAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"MotionAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
            //0（正常） 1（被撬）如果是打开则被撬
            if (baojing2.isSwitchOn()) {
                sb.append("\"TamperAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"TamperAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
        }
        if (model.equals(ConstantConfigure.MODEL_SUIJINTANCEQI)) {
            //0（关闭） 1（打开）
            if (baojing1.isSwitchOn()) {
                sb.append("\"WaterAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"WaterAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }
            //0（正常） 1（被撬）如果是打开则被撬
            if (baojing2.isSwitchOn()) {
                sb.append("\"TamperAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("1");
                sb.append(entity.toString());
                sb.append(",");
            } else {
                sb.append("\"TamperAlarm\" :");
                Key_ValueEntity entity = new Key_ValueEntity();
                entity.setValue("0");
                sb.append(entity.toString());
                sb.append(",");
            }

            sb.append("\"BatteryPercentage\" :");
            Key_ValueEntity entity_dianliang = new Key_ValueEntity();
            entity_dianliang.setValue(String.valueOf(dianliang.getProgress()));
            sb.append(entity_dianliang.toString());
            sb.append(",");
            sb.append("\"Rssi\" :");
            Key_ValueEntity entity_xinhao = new Key_ValueEntity();
            entity_xinhao.setValue(String.valueOf(xinhaoqiangdu.getProgress()));
            sb.append(entity_xinhao.toString());
            sb.append(",");
        }
        sb.append("}");
        relationDeviceTable.setTrigger_condition(sb.toString());
        relationDeviceTable.setQingJingTable_id(qingJingTable_id);
        List<LocalDb_RelationDeviceTable> lists = DataSupport.where("uuid = ?", uuid).find(LocalDb_RelationDeviceTable.class);
        Log.i("info", "此时的关联表长度=" + lists.size());
        boolean is_same = false;
        int table_id = 0;
        if (lists != null && lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                if (lists.get(i).getTrigger_condition() != null && lists.get(i).getTrigger_condition().equals(relationDeviceTable.getTrigger_condition())) {
                    is_same = true;
                    table_id = lists.get(i).getId();
                }
            }
        }
        //如果相等则updata
        if (is_same) {
            relationDeviceTable.update(table_id);
        } else {
            relationDeviceTable.save();
        }
        finish();
        toastActBtm("保存成功");

    }

    private void setView() {
        img = (ImageView) findViewById(R.id.activity_devicecontrol_img);
        dianliang_text = (TextView) findViewById(R.id.activity_devicecontrol_dianliang_text);
        xinhaoqiangdu_text = (TextView) findViewById(R.id.activity_devicecontrol_xinhaoqiangdu_text);
        dianliang = (SignSeekBar) findViewById(R.id.activity_devicecontrol_dianliang);
        xinhaoqiangdu = (SignSeekBar) findViewById(R.id.activity_devicecontrol_xinhaoqiangdu);
        baojing1_text = (TextView) findViewById(R.id.activity_devicecontrol_baojing1_text);
        baojing2_text = (TextView) findViewById(R.id.activity_devicecontrol_baojing2_text);
        baojing3_text = (TextView) findViewById(R.id.activity_devicecontrol_baojing3_text);
        baojing1 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_baojing1);
        baojing2 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_baojing2);
        baojing3 = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_baojing3);
        baojing1_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_baojing1_ll);
        baojing2_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_baojing2_ll);
        baojing3_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_baojing3_ll);
        dianliang_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_dianliang_ll);
        xinhaoqiangdu_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_xinhaoqiangdu_ll);
        //modify for relationdevice start
        relationdevice_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_ll);
        relationdevice_text = (TextView) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_text);
        relationdevice_ll.setVisibility(View.VISIBLE);
        relationdevice_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeviceRelation_BaoJingActivity.this, QingJingListActivity.class);
                startActivityForResult(intent, ConstantConfigure.DEFAULT_ZERO);
            }
        });
        //modify for relationdevice end

        String imgurl = null;
        setCanClick(true);
        if (model.equals(ConstantConfigure.MODEL_YANWUTANCEQI)) {
            imgurl = ConstantConfigure.IMGURL_YANWUTANCEQI_00671E3E;
            baojing2_ll.setVisibility(View.GONE);
            baojing3_ll.setVisibility(View.GONE);
            baojing1_text.setText("烟雾报警");
        }
        if (model.equals(ConstantConfigure.MODEL_MENCIGANYING)) {
            imgurl = ConstantConfigure.IMGURL_MENCIGANYING_00331E3B;
            baojing3_ll.setVisibility(View.GONE);
            baojing1_text.setText("门磁报警");
            baojing2_text.setText("防撬报警");
        }
        if (model.equals(ConstantConfigure.MODEL_MEIQITANCEQI)) {
            imgurl = ConstantConfigure.IMGURL_QITITANCEQI_00121E3C;
            dianliang_ll.setVisibility(View.GONE);
            xinhaoqiangdu_ll.setVisibility(View.GONE);
            baojing2_ll.setVisibility(View.GONE);
            baojing3_ll.setVisibility(View.GONE);
            baojing1_text.setText("煤气报警");

        }
        if (model.equals(ConstantConfigure.MODEL_RENTIGANYING)) {
            imgurl = ConstantConfigure.IMGURL_RENTIGANYING_001A1E10;
            baojing1_ll.setVisibility(View.VISIBLE);
            baojing1_text.setText("检测人体");
            baojing2_ll.setVisibility(View.VISIBLE);
            baojing3_ll.setVisibility(View.GONE);
            baojing2_text.setText("防撬报警");
        }
        if (model.equals(ConstantConfigure.MODEL_SUIJINTANCEQI)) {
            imgurl = ConstantConfigure.IMGURL_SHUIJINTANCEQI_005D1E3E;
            baojing3_ll.setVisibility(View.GONE);
            baojing1_text.setText("浸水报警");
            baojing2_text.setText("防撬报警");
        }
        if (imgurl != null) {
            GliderImageLoaderUtil.load(this, imgurl, img);
        }
        dianliang.getConfigBuilder()
                .sectionTextColor(ContextCompat.getColor(DeviceRelation_BaoJingActivity.this, R.color.colorPrimary))
                .sectionTextSize(15)
                .setUnit("%")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                .build();
        xinhaoqiangdu.getConfigBuilder()
                .sectionTextColor(ContextCompat.getColor(DeviceRelation_BaoJingActivity.this, R.color.colorPrimary))
                .sectionTextSize(15)
                .setUnit("%")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                .build();

    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);
                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                fillData(obj, obj.getString("uuid"));
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    private void fillData(JSONObject obj, String uuid) {
        if (uuid == null || !uuid.equals(uuid)) {
            return;
        }
        if (model.equals(ConstantConfigure.MODEL_YANWUTANCEQI)) {
            Key_ValueEntity bean_dianliang = JSON.parseObject(obj.getString("BatteryPercentage"), Key_ValueEntity.class);
            Key_ValueEntity bean_xinhao = JSON.parseObject(obj.getString("Rssi"), Key_ValueEntity.class);
            Key_ValueEntity bean_yanwu = JSON.parseObject(obj.getString("SmokeAlarm"), Key_ValueEntity.class);
            dianliang.setProgress(Long.parseLong(bean_dianliang.getValue()));
            xinhaoqiangdu.setProgress(Long.parseLong(bean_xinhao.getValue()));
            if (bean_yanwu.getValue().equals("0")) {
                baojing1.setSwitchOn(false);
            } else {
                baojing1.setSwitchOn(true);
            }
            baojing1.invalidate();
        }
        if (model.equals(ConstantConfigure.MODEL_MENCIGANYING)) {
            Key_ValueEntity bean_dianliang = JSON.parseObject(obj.getString("BatteryPercentage"), Key_ValueEntity.class);
            Key_ValueEntity bean_xinhao = JSON.parseObject(obj.getString("Rssi"), Key_ValueEntity.class);
            Key_ValueEntity bean_menci = JSON.parseObject(obj.getString("ContactAlarm"), Key_ValueEntity.class);
            Key_ValueEntity bean_fangqiao = JSON.parseObject(obj.getString("TamperAlarm"), Key_ValueEntity.class);
            dianliang.setProgress(Long.parseLong(bean_dianliang.getValue()));
            xinhaoqiangdu.setProgress(Long.parseLong(bean_xinhao.getValue()));
            if (bean_menci.getValue().equals("0")) {
                baojing1.setSwitchOn(false);
            } else {
                baojing1.setSwitchOn(true);
            }
            baojing1.invalidate();
            if (bean_fangqiao.getValue().equals("0")) {
                baojing2.setSwitchOn(false);
            } else {
                baojing2.setSwitchOn(true);
            }
            baojing2.invalidate();
        }
        if (model.equals(ConstantConfigure.MODEL_MEIQITANCEQI)) {
            Key_ValueEntity bean_meiqixielou = JSON.parseObject(obj.getString("GasAlarm"), Key_ValueEntity.class);
            if (bean_meiqixielou.getValue().equals("0")) {
                baojing1.setSwitchOn(false);
            } else {
                baojing1.setSwitchOn(true);
            }
            baojing1.invalidate();
        }
        if (model.equals(ConstantConfigure.MODEL_RENTIGANYING)) {
            Key_ValueEntity bean_dianliang = JSON.parseObject(obj.getString("BatteryPercentage"), Key_ValueEntity.class);
            Key_ValueEntity bean_xinhao = JSON.parseObject(obj.getString("Rssi"), Key_ValueEntity.class);
            Key_ValueEntity switch_1 = JSON.parseObject(obj.getString("MotionAlarm"), Key_ValueEntity.class);
            Key_ValueEntity switch_2 = JSON.parseObject(obj.getString("TamperAlarm"), Key_ValueEntity.class);
            dianliang.setProgress((float) Double.parseDouble(bean_dianliang.getValue()));
            xinhaoqiangdu.setProgress((float) Double.parseDouble(bean_xinhao.getValue()));
            if (switch_1.getValue().equals("0")) {
                baojing1.setSwitchOn(false);
            } else {
                baojing1.setSwitchOn(true);
            }
            baojing1.invalidate();
            if (switch_2.getValue().equals("0")) {
                baojing2.setSwitchOn(false);
            } else {
                baojing2.setSwitchOn(true);
            }
            baojing2.invalidate();
        }
        if (model.equals(ConstantConfigure.MODEL_SUIJINTANCEQI)) {
            Key_ValueEntity bean_dianliang = JSON.parseObject(obj.getString("BatteryPercentage"), Key_ValueEntity.class);
            Key_ValueEntity bean_xinhao = JSON.parseObject(obj.getString("Rssi"), Key_ValueEntity.class);
            Key_ValueEntity bean_fangqiao = JSON.parseObject(obj.getString("TamperAlarm"), Key_ValueEntity.class);
            Key_ValueEntity bean_jinshui = JSON.parseObject(obj.getString("WaterAlarm"), Key_ValueEntity.class);

            dianliang.setProgress(Long.parseLong(bean_dianliang.getValue()));
            xinhaoqiangdu.setProgress(Long.parseLong(bean_xinhao.getValue()));
            if (bean_fangqiao.getValue().equals("0")) {
                baojing2.setSwitchOn(false);
            } else {
                baojing2.setSwitchOn(true);
            }
            if (bean_jinshui.getValue().equals("0")) {
                baojing1.setSwitchOn(false);
            } else {
                baojing1.setSwitchOn(true);
            }
            baojing2.invalidate();
            baojing1.invalidate();
        }
    }

    private void setCanClick(boolean value) {
        LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
        if (value) {
        } else {
            ll.setOnClickListener(null);
            ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toastActBtm("不可点击");
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String name = data.getStringExtra("name");
            qingJingTable_id = data.getIntExtra("id", 0);
            relationdevice_text.setText(name);
        }
    }
}
